package com.example.api;

import com.example.annotation.UserLoginToken;
import com.example.entity.JsonBean;
import com.example.entity.User;
import com.example.service.TokenService;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class UserApi {


    @Autowired
    UserService userService;
    @Autowired
    TokenService tokenService;

    static Map<String, Object> objectMap = Collections.synchronizedMap(new HashMap<String, Object>());
    @GetMapping("/all")
    public List<User> findAll(){
        return userService.findAll();
    }

    @PostMapping("login")
    public Object login(User user){
        User userForBase=userService.findByUsername(user);
        if(userForBase==null){

            return JsonBean.error("登录失败,用户不存在","");
        }else {
            if (!userForBase.getPassword().equals(user.getPassword())){
                return JsonBean.error("登录失败,密码错误","");
            }else {
                String token = tokenService.getToken(userForBase);
                objectMap.put("token", token);
                objectMap.put("user", userForBase);
                return objectMap;
            }
        }
    }

    @UserLoginToken
    @GetMapping("/getMessage")
    public String getMessage(){
        return "你已通过验证";
    }
}
